import {createSlice} from '@reduxjs/toolkit'
import request from '@/utils/request.js'

// 账单相关store
export const billSlice = createSlice({
    name: 'bill',
    // 数据状态state
    initialState: {
        billList: []
    },
    reducers: {
        // 同步修改方法
        setBillList(state,action) {
            state.billList = action.payload
        },
        setBillData(state,action) {
            state.billList.unshift(action.payload)
        }
    }
})

// 解构actionCreater函数
export const {setBillList,setBillData} = billSlice.actions

// 异步
export const getBillList = ()=> {
    return async (dispatch) => {
       const res = await request.get('/list')
       // 按时间降序排序
       res.data.sort((a, b) => new Date(b.date) - new Date(a.date));

       // 触发同步reducer
       dispatch(setBillList(res.data))

    }
}

// 新增一笔账单
export const addBillData = (data) => {
    return async (dispatch) => {
        const res = await request.post('/list',data)
        dispatch(setBillData(res.data))
    }
}

// 导出reducer
export default billSlice.reducer